package com.fc.handler;

import com.fc.exception.BaseException;
import com.fc.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 捕获业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }


    /**
     * 拦截数据库键唯一异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result duplicateExceptionHandle(SQLIntegrityConstraintViolationException ex) {
        log.error("异常信息：{}", ex.getMessage());
        String errMsg = ex.getMessage();
        if (errMsg.contains("Duplicate entry")) {
            String msg = errMsg.split(" ")[2];
            return Result.error(msg + "已存在");
        } else {
            return Result.error("未知异常");
        }
    }
}
